package com.tiger.admin.http.common.member;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.admin.Db;
import com.tiger.db.entity.Member;
import com.tiger.db.entity.Menu;
import com.tiger.db.entity.Role;
import com.tiger.utils.ResponseUtil;
import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.UUID;

@Service
public class MemberService {
    private final Db db;

    public MemberService(Db db) {
        this.db = db;
    }

    public String buildPassword(String password, String salt) {
        password = sha256Hash(password);
        return sha256Hash(password + salt);
    }

    public String generateSalt() {
        // 生成标准形式的UUID
        String[] uuids = UUID.randomUUID().toString().split("-");


        return uuids[uuids.length - 1];
    }

    public static String sha256Hash(String input) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hashBytes = digest.digest(input.getBytes(StandardCharsets.UTF_8));
            return Hex.encodeHexString(hashBytes).toLowerCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<Menu> permissionMenu(Long memberId, String... fields) {
        Member member = db.member.getOne(new QueryWrapper<Member>().select("roles", "can_super").eq("id", memberId));
        if(member == null) return null;

        List<Menu> menus = new ArrayList<>();

        //是超级管理员，有所有菜单权限
        if(member.isCanSuper()) {
            menus = db.menu.list(new QueryWrapper<Menu>().orderByDesc("sort").orderByAsc("id").select(fields));
        }else {
            QueryWrapper<Role> query =  new QueryWrapper<>();
            query.select("menus");

            if(member.getRoles() == null || member.getRoles().length == 0) {
                return menus;
            }

            if(member.getRoles().length == 1) {
                query.eq("id", member.getRoles()[0]);
            }else {
                query.in("id", member.getRoles());
            }


            List<Role> roles = db.role.list(query);
            List<Long> menuIds = new ArrayList<>();
            for(Role role : roles) {
                Long[] ids = role.getMenus();
                if(ids != null && ids.length > 0) {
                    for(Long id : ids) {
                        if(!menuIds.contains(id)) {
                            menuIds.add(id);
                        }
                    }
                }
            }

            if(!menuIds.isEmpty()) {
                menus = db.menu.list(new QueryWrapper<Menu>().orderByDesc("sort").orderByAsc("id").select(fields).in("id", menuIds));
            }

        }

        return  menus;
    }


    public boolean checkPassword(String password, Long id) {
        Member member = db.member.getOne(new LambdaQueryWrapper<Member>().select(Member::getPassword, Member::getSalt).eq(Member::getId, id));

        return Objects.equals(buildPassword(password, member.getSalt()), member.getPassword());

    }
}
